package com.xxc.hs.fragment;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import cn.com.newland.nle_sdk.responseEntity.SensorReaTimeData;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.CloudService;
import cn.com.newland.nle_sdk.util.CloudServiceListener;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.tplink.applibs.util.TPByteArrayJNI;
import com.tplink.sdk.tpopensdk.TPOpenSDK;
import com.tplink.sdk.tpopensdk.TPPlayer;
import com.tplink.sdk.tpopensdk.TPSDKContext;
import com.tplink.sdk.tpopensdk.common.TPSDKCommon;
import com.tplink.sdk.tpopensdk.openctx.IPCDevice;
import com.tplink.sdk.tpopensdk.openctx.IPCDeviceContext;
import com.tplink.sdk.tpopensdk.openctx.IPCReqListener;
import com.tplink.sdk.tpopensdk.openctx.IPCReqResponse;
import com.xxc.hs.R;
import com.xxc.hs.bean.CloudInfo;
import com.xxc.hs.bean.DataInfo;
import com.xxc.hs.bean.UserInfo;
import com.xxc.hs.db.DataHelper;
import com.xxc.hs.funActivity.WaringActivity;
import com.xxc.hs.funActivity.waring.ScreenshotManager;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SuppressWarnings("ALL")
public class SafeFragment extends Fragment {
    private static final String TAG = "SafeFragment";

    // 顶部状态信息控件
    private TextView headerCameraStatus, headerAlarmStatus, headerDoorStatus;
    private View headerCameraIndicator, headerAlarmIndicator, headerDoorIndicator;


    // 摄像头监控区域控件
    private View video;     //离线显示
    private ImageView ivCameraPreview, btnCameraUp, btnCameraLeft, btnCameraRight, btnCameraDown, btnCameraToggle;
    private View llCameraOffline, llCameraControls;


    // 环境数据控件
    private TextView tvTemperatureValue, tvHumidityValue;

    // 传感器状态控件
    private TextView tvSmoke, tvFire, tvLaser;

    // 设备控制控件
    private CardView cardDeviceControl;
    private ImageView ivLamp, btnLamp, ivDoor, btnDoor, ivFan, btnFan;

    private final String Tp_ip = "192.168.1.13";        //摄像头的IP地址
    private final String RFID = "E2 80 69 95 00 00 40 12 64 94 B6 A0";
    private TPOpenSDK m_TPOpenSDK = TPOpenSDK.getInstance();
    private TPSDKContext m_TPSDKContext = null;
    private IPCDeviceContext m_IPCDeviceContext = null;
    private IPCDevice m_IPCDevice = null;
    private TPPlayer m_TPPlayer = null;

    private ObjectAnimator animator;        //风扇动画
    private MediaPlayer mediaPlayer;        //报警播放

    private boolean can_play = false;
    private boolean btn_camera = false;
    private boolean door_flag = false;
    private boolean lamp_flag = false;
    private boolean fan_flag = false;

    private boolean uhf_flag = true;
    private boolean laser_flag = true;

    //获取数据
    private CloudService cloudService;
    private boolean isDataFetching = false;
    private Handler dataHandler;
    private Runnable dataRunnable;
    private static final int DATA_FETCH_INTERVAL = 200;


    //数据存储
    private Handler storageHandler;
    private Runnable storageRunnable;
    private static final int STORAGE_INTERVAL = 1000; // 1秒间隔


    //图表相关变量
    private LineChart chartEnvironment;
    private LineData lineData;
    private LineDataSet tempDataSet, humDataSet;
    private List<Entry> tempEntries, humEntries;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_safe, container, false);

        try {
            if (CloudInfo.getCloudService() == null) CloudInfo.setCloudService();

            initViews(view);
            initAnimator();
            initStorageTask();      //初始化数据存储任务
            initChart();            //初始化图表

            new Thread(new Runnable() {
                @Override
                public void run() {
                    initTp();
                }
            }).start();

            initDataHandler();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        try {
            if (CloudInfo.getCloudService() != null) {
                cloudService = CloudInfo.getCloudService();
            }
            stop_show_video();

            btnCameraToggle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btn_camera = !btn_camera;
                    if (btn_camera)
                        show_video();
                    else
                        stop_show_video();
                }
            });

            btnCameraUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (can_play)
                        m_IPCDeviceContext.reqMotorMoveBy(m_IPCDevice, null, 0, -20, -1);
                }
            });

            btnCameraDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (can_play)
                        m_IPCDeviceContext.reqMotorMoveBy(m_IPCDevice, null, 0, 20, -1);
                }
            });

            btnCameraLeft.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (can_play)
                        m_IPCDeviceContext.reqMotorMoveBy(m_IPCDevice, null, -20, 0, -1);
                }
            });

            btnCameraRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (can_play)
                        m_IPCDeviceContext.reqMotorMoveBy(m_IPCDevice, null, 20, 0, -1);
                }
            });

            btnDoor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    door_flag = !door_flag;
                    addButtonAnimation(v);
                    if (door_flag) {
                        openDoor();
                        updateDoor(1);
                    } else {
                        closeDoor();
                        updateDoor(0);
                    }
                }
            });

            btnLamp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    lamp_flag = !lamp_flag;
                    addButtonAnimation(v);
                    if (lamp_flag) {
                        openWaringLamp();
                        updateLamp(1);
                    } else {
                        closeWaringLamp();
                        updateLamp(0);
                    }
                }
            });

            btnFan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    fan_flag = !fan_flag;
                    addButtonAnimation(v);
                    if (fan_flag) {
                        openFan();
                        updateFan(1);
                    } else {
                        closeFan();
                        updateFan(0);
                    }
                }
            });

            startDataFetching();

            startStorageTask();     //启动数据存储任务

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据
     */
    private void getData() {
        try {
            cloudService.getSensorsRealTimeData(CloudInfo.ProjectId, new CloudServiceListener<BaseResponseEntity<List<SensorReaTimeData>>>() {
                @Override
                protected void onResponse(BaseResponseEntity<List<SensorReaTimeData>> listBaseResponseEntity) {
                    if (listBaseResponseEntity.getStatus() != 0) {
                        Log.e(TAG, "数据获取失败");
                        return;
                    }

                    String uhf = "";
                    String laser = "";

                    for (SensorReaTimeData item : listBaseResponseEntity.getResultObj()) {
                        String apiTag = item.getApiTag();
                        String data = item.getValue();

                        if (apiTag.equals(CloudInfo.UHF))
                            uhf = data;

                        if (apiTag.equals(CloudInfo.LASER))
                            laser = data;

                        if (apiTag.equals(CloudInfo.ALARM) && data.equals("1")) {
                            if (tvSmoke.getText().toString().equals("无烟") && tvFire.getText().toString().equals("无火") && !lamp_flag) {
                                closeWaringLamp();
                                updateLamp(0);
                            }
                        }
                        parseData(apiTag, data);
                    }

                    handleRFIDDetected(uhf, laser);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 解析数据
     */
    private void parseData(String apiTag, String data) {
        try {
            if (CloudInfo.UHF.equals(apiTag)) {
                return;
            }
            float value = 0;
            try {
                BigDecimal bd = new BigDecimal(data).setScale(3, RoundingMode.HALF_UP);
                value = bd.floatValue();
            } catch (Exception e) {
                e.printStackTrace();
            }

            Log.e(TAG, "设备: " + apiTag + "  数值: " + value);
            switch (apiTag) {
                case CloudInfo.TEMP:
                    updateTemp(value);
                    break;
                case CloudInfo.HUM:
                    updateHum(value);
                    break;
                case CloudInfo.LASER:
                    updateLaser(value);
                    break;
                case CloudInfo.SMOKE:
                    updateSmoke(value);
                    break;
                case CloudInfo.FIRE:
                    updateFire(value);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 存储数据
     */
    private void saveSensorDataToDatabase() {
        try {
            // 从UI或数据模型获取当前传感器值
            String tempValue = tvTemperatureValue.getText().toString();
            String humValue = tvHumidityValue.getText().toString();

            // 获取烟雾和火焰状态（0或1）
            int smokeValue = tvSmoke.getText().toString().equals("有烟") ? 1 : 0;
            int fireValue = tvFire.getText().toString().equals("有火") ? 1 : 0;

            String timeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 创建DataInfo对象并存储到数据库
            DataInfo dataInfo = new DataInfo(tempValue, humValue, smokeValue, fireValue, timeString);
            DataHelper.getInstance(requireContext()).InsertData(dataInfo);

            Log.d(TAG, "数据已存储 - 时间: " + timeString +
                    ", 温度: " + tempValue +
                    ", 湿度: " + humValue +
                    ", 烟雾: " + smokeValue +
                    ", 火焰: " + fireValue);

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateChartData();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理RFID检测逻辑
     */
    private void handleRFIDDetected(String uhf, String laser) {
        try {
            if (RFID.equals(uhf) && uhf_flag) {
                uhf_flag = false;
                door_flag = true;
                openDoor();
                updateDoor(1);

                //延时15秒关闭门阀
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    door_flag = false;
                    closeDoor();
                    updateDoor(0);
                }, 15000);

            } else if (!RFID.equals(uhf)) {
                uhf_flag = true;
                if (laser.equals("1") && laser_flag) {
                    laser_flag = false;
                    //截屏
                    Log.e(TAG, "有人闯入");
                    takeCameraScreenshot();
                } else if (laser.equals("0")) {
                    laser_flag = true;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 摄像头截图
     */
    private void takeCameraScreenshot() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (null != m_TPPlayer) {
                        ScreenshotManager screenshotManager = new ScreenshotManager(getContext(), getActivity());
                        String result = screenshotManager.saveScreenshot(m_TPPlayer);

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.e(TAG, "截图保存结果: " + result);
                                Toast.makeText(getContext(), result, Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 开始获取数据
     */
    private void startDataFetching() {
        try {
            if (!isDataFetching) {
                isDataFetching = true;
                // 立即执行一次获取
                dataHandler.post(dataRunnable);
                Log.d(TAG, "开始数据获取");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止获取数据
     */
    private void stopDataFetching() {
        try {
            if (isDataFetching) {
                isDataFetching = false;
                // 移除所有待执行的任务
                dataHandler.removeCallbacks(dataRunnable);
                Log.d(TAG, "停止数据获取");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新温度标签值
     */
    private void updateTemp(float value) {
        try {
            tvTemperatureValue.post(new Runnable() {
                @Override
                public void run() {
                    tvHumidityValue.setText(value + "");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新湿度标签值
     */
    private void updateHum(float value) {
        try {
            tvHumidityValue.post(new Runnable() {
                @Override
                public void run() {
                    tvHumidityValue.setText(value + "");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新激光标签值
     */
    private void updateLaser(float value) {
        try {
            tvLaser.post(new Runnable() {
                @Override
                public void run() {
                    if (value == 1.0) {
                        tvLaser.setText("有人");
                    } else {
                        tvLaser.setText("无人");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新烟雾标签值
     */
    private void updateSmoke(float value) {
        try {
            tvSmoke.post(new Runnable() {
                @Override
                public void run() {
                    if (value == 1.0) {
                        tvSmoke.setText("有烟");
                        tvSmoke.setTextColor(Color.RED);
                        lamp_flag = true;
                        openWaringLamp();
                        updateLamp(1);

                    } else {
                        tvSmoke.setText("无烟");
                        tvSmoke.setTextColor(Color.BLACK);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新火焰标签值
     */
    private void updateFire(float value) {
        try {
            tvFire.post(new Runnable() {
                @Override
                public void run() {
                    if (value == 1.0) {
                        tvFire.setText("有火");
                        tvFire.setTextColor(Color.RED);
                        lamp_flag = true;
                        openWaringLamp();
                        updateLamp(1);
                    } else {
                        tvFire.setText("无火");
                        tvFire.setTextColor(Color.BLACK);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新报警灯状态
     */
    private void updateLamp(int value) {
        try {
            ivLamp.post(new Runnable() {
                @Override
                public void run() {
                    if (value == 1) {
                        //报警灯打开
                        headerAlarmIndicator.setBackgroundResource(R.drawable.shape_indicator_red);
                        headerAlarmStatus.setText("异常");

                        ivLamp.setImageResource(R.drawable.pic_alarm_on);
                        btnLamp.setImageResource(R.drawable.btn_list_switch_on);
                    } else {
                        //报警灯关闭
                        headerAlarmIndicator.setBackgroundResource(R.drawable.shape_indicator_green);
                        headerAlarmStatus.setText("正常");

                        ivLamp.setImageResource(R.drawable.pic_alarm_off);
                        btnLamp.setImageResource(R.drawable.btn_list_switch_off);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 更新门阀状态
     */
    private void updateDoor(int value) {
        try {
            ivDoor.post(new Runnable() {
                @Override
                public void run() {
                    if (value == 1) {
                        //门阀打开
                        headerDoorIndicator.setBackgroundResource(R.drawable.shape_indicator_red);
                        headerDoorStatus.setText("打开");

                        ivDoor.setImageResource(R.drawable.pic_cartoon_gate_2);
                        btnDoor.setImageResource(R.drawable.btn_list_switch_on);
                    } else {
                        //门阀关闭
                        headerDoorIndicator.setBackgroundResource(R.drawable.shape_indicator_green);
                        headerDoorStatus.setText("关闭");

                        ivDoor.setImageResource(R.drawable.pic_cartoon_gate_1);
                        btnDoor.setImageResource(R.drawable.btn_list_switch_off);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 更新风扇状态
     */
    private void updateFan(int value) {
        try {
            btnFan.post(new Runnable() {
                @Override
                public void run() {
                    if (value == 1) {
                        //风扇打开
                        btnFan.setImageResource(R.drawable.btn_list_switch_on);
                        startFanAnimation();
                    } else {
                        //风扇关闭
                        btnFan.setImageResource(R.drawable.btn_list_switch_off);
                        stopFanAnimation();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 打开门阀
     */
    private void openDoor() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cloudService.control(CloudInfo.GatewayId, CloudInfo.DOORPUT, false, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });

                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    cloudService.control(CloudInfo.GatewayId, CloudInfo.DOORBACK, true, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });

                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 关闭门阀
     */
    private void closeDoor() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cloudService.control(CloudInfo.GatewayId, CloudInfo.DOORBACK, false, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });

                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    cloudService.control(CloudInfo.GatewayId, CloudInfo.DOORPUT, true, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 打开报警灯
     */
    private void openWaringLamp() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cloudService.control(CloudInfo.GatewayId, CloudInfo.ALARM, true, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {
                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭报警灯
     */
    private void closeWaringLamp() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cloudService.control(CloudInfo.GatewayId, CloudInfo.ALARM, false, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 打开风扇
     */
    private void openFan() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cloudService.control(CloudInfo.GatewayId, CloudInfo.FAN, true, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {
                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭风扇
     */
    private void closeFan() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    cloudService.control(CloudInfo.GatewayId, CloudInfo.FAN, false, new CloudServiceListener<BaseResponseEntity>() {
                        @Override
                        protected void onResponse(BaseResponseEntity baseResponseEntity) {

                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 开始旋转
     */
    private void startFanAnimation() {
        try {
            if (animator != null && !animator.isRunning()) {
                animator.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止旋转
     */
    private void stopFanAnimation() {
        try {
            if (animator != null && animator.isRunning()) {
                animator.end();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 风扇动画初始化
     */
    private void initAnimator() {
        try {
            animator = ObjectAnimator.ofFloat(ivFan, "rotation", 0f, 360f);

            // 设置动画时长(毫秒)
            animator.setDuration(200);

            // 设置动画重复次数
            // ObjectAnimator.INFINITE 表示无限循环
            animator.setRepeatCount(ObjectAnimator.INFINITE);

            // 设置重复模式
            // ValueAnimator.RESTART 表示重新开始
            animator.setRepeatMode(ValueAnimator.RESTART);

            // 设置插值器，实现均衡旋转效果 - LinearInterpolator 表示线性插值，匀速旋转
            animator.setInterpolator(new android.view.animation.LinearInterpolator());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 启动数据存储任务
     */
    private void startStorageTask() {
        try {
            if (storageHandler != null && storageRunnable != null) {
                // 立即执行一次存储
                storageHandler.post(storageRunnable);
                Log.d(TAG, "开始数据存储任务");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止数据存储任务
     */
    private void stopStorageTask() {
        try {
            if (storageHandler != null && storageRunnable != null) {
                // 移除所有待执行的存储任务
                storageHandler.removeCallbacks(storageRunnable);
                Log.d(TAG, "停止数据存储任务");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 开始播放
     */
    private void startAudio(String filePath) {
        try {
            // 重置MediaPlayer
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();

            // 设置assets中的音频数据源
            mediaPlayer.setDataSource(requireActivity().getAssets().openFd(filePath));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 停止播放
     */
    private void stopAudio() {
        try {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                try {
                    // 重置MediaPlayer以便重新播放
                    mediaPlayer.reset();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }


    /**
     * 添加按钮点击动画效果
     */
    private void addButtonAnimation(View view) {
        try {
            view.animate().scaleX(1.1f).scaleY(1.1f)
                    .setDuration(100)
                    .withEndAction(() -> view.animate().scaleX(1f).scaleY(1f).setDuration(100).start());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化数据获取Handler
     */
    private void initDataHandler() {
        try {
            dataHandler = new Handler();
            dataRunnable = new Runnable() {
                @Override
                public void run() {
                    if (isDataFetching) {
                        getData();
                        // 循环执行数据获取
                        dataHandler.postDelayed(this, DATA_FETCH_INTERVAL);
                    }
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭摄像头画面
     */
    private void stop_show_video() {
        try {
            headerCameraIndicator.setBackgroundResource(R.drawable.shape_indicator_red);
            headerCameraStatus.setText("离线");

            btnCameraToggle.setBackgroundResource(R.drawable.bg_camera_toggle_close);
            video.setVisibility(View.INVISIBLE);
            ivCameraPreview.setVisibility(View.VISIBLE);
            llCameraOffline.setVisibility(View.VISIBLE);
            if (null != m_TPPlayer) {
                m_TPPlayer.stop();
                m_TPPlayer.release();
                m_TPPlayer = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "摄像头画面停止播放异常: " + e.toString());
        }
    }


    /**
     * 显示摄像头画面
     */
    private void show_video() {
        try {
            headerCameraIndicator.setBackgroundResource(R.drawable.shape_indicator_green);
            headerCameraStatus.setText("在线");

            btnCameraToggle.setBackgroundResource(R.drawable.bg_camera_toggle_open);
            video.setVisibility(View.VISIBLE);
            ivCameraPreview.setVisibility(View.INVISIBLE);
            llCameraOffline.setVisibility(View.INVISIBLE);

            if (can_play) {
                m_TPPlayer = this.m_TPOpenSDK.createPlayer(getActivity());
                m_TPPlayer.setViewHolder((ViewGroup) video);
                m_TPPlayer.setPlayerCallback(new TPPlayer.PlayerCallback() {
                    @Override
                    public int onPlayStatusChange(int i, int i1) {
                        return 0;
                    }

                    @Override
                    public int onRecordStatusChange(int i, int i1, String s) {
                        return 0;
                    }

                    @Override
                    public int onSnapshot(int i, String s) {
                        return 0;
                    }

                    @Override
                    public int onPlayTimeUpdate(long l) {
                        return 0;
                    }

                    @Override
                    public int onRecordDurationUpdate(long l) {
                        return 0;
                    }

                    @Override
                    public int onDataStatistics(long l, double v) {
                        return 0;
                    }

                    @Override
                    public int onChangeQuality(int i) {
                        return 0;
                    }

                    @Override
                    public int onDataRecv(TPByteArrayJNI tpByteArrayJNI) {
                        return 0;
                    }

                    @Override
                    public int onYUVDataRecv(ByteBuffer[] byteBuffers, int[] ints, int i, int i1) {
                        return 0;
                    }
                });
                m_TPPlayer.startRealPlay(m_IPCDevice, TPSDKCommon.Quality.QUALITY_CLEAR);
            }
        } catch (Exception e) {
            Log.e(TAG, "摄像头画面显示异常: " + e.toString());
        }
    }


    /**
     * 更新图表数据
     */
    private void updateChartData() {
        try {
            // 从数据库获取最近20条数据
            List<DataInfo> dataList = DataHelper.getInstance(requireContext()).getRecentData(20);

            // 清空现有数据
            tempEntries.clear();
            humEntries.clear();

            // 填充温度和湿度数据
            for (int i = 0; i < dataList.size(); i++) {
                DataInfo data = dataList.get(i);
                try {
                    float temp = Float.parseFloat(data.getTemp());
                    float hum = Float.parseFloat(data.getHum());

                    // 使用索引作为x轴值，实际应用中可以使用时间戳
                    tempEntries.add(new Entry(i, temp));
                    humEntries.add(new Entry(i, hum));
                } catch (NumberFormatException e) {
                    Log.e(TAG, "数据格式错误: " + e.getMessage());
                }
            }

            // 更新数据集
            tempDataSet.setValues(tempEntries);
            humDataSet.setValues(humEntries);

            // 更新x轴标签
            if (dataList.size() > 0) {
                XAxis xAxis = chartEnvironment.getXAxis();
                xAxis.setLabelCount(dataList.size(), true);
            }

            // 刷新图表
            lineData.notifyDataChanged();
            chartEnvironment.notifyDataSetChanged();
            chartEnvironment.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化图表
     */
    private void initChart() {
        try {
            // 清除所有数据
            chartEnvironment.clear();

            // 设置图表基本属性
            chartEnvironment.setDrawGridBackground(false);
            chartEnvironment.setTouchEnabled(true);
            chartEnvironment.setDragEnabled(true);
            chartEnvironment.setScaleEnabled(true);
            chartEnvironment.setPinchZoom(true);

            // 获取图例并设置位置
            Legend legend = chartEnvironment.getLegend();
            legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
            legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
            legend.setDrawInside(false);

            // 设置x轴
            XAxis xAxis = chartEnvironment.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setDrawGridLines(false);
            xAxis.setLabelRotationAngle(45f);

            // 设置y轴
            YAxis leftYAxis = chartEnvironment.getAxisLeft();
            leftYAxis.setAxisMinimum(0f);
            leftYAxis.setAxisMaximum(100f);
            leftYAxis.setLabelCount(5, false);

            YAxis rightYAxis = chartEnvironment.getAxisRight();
            rightYAxis.setEnabled(false); // 禁用右侧y轴

            // 初始化数据集合
            tempEntries = new ArrayList<>();
            humEntries = new ArrayList<>();

            // 创建温度数据集
            tempDataSet = new LineDataSet(tempEntries, "温度 (°C)");
            tempDataSet.setColor(Color.RED);
            tempDataSet.setCircleColor(Color.RED);
            tempDataSet.setLineWidth(2f);
            tempDataSet.setCircleRadius(4f);
            tempDataSet.setDrawCircleHole(false);
            tempDataSet.setValueTextSize(10f);
            tempDataSet.setDrawFilled(true);

            // 创建湿度数据集
            humDataSet = new LineDataSet(humEntries, "湿度 (%)");
            humDataSet.setColor(Color.BLUE);
            humDataSet.setCircleColor(Color.BLUE);
            humDataSet.setLineWidth(2f);
            humDataSet.setCircleRadius(4f);
            humDataSet.setDrawCircleHole(false);
            humDataSet.setValueTextSize(10f);
            humDataSet.setDrawFilled(true);

            // 创建LineData并添加数据集
            lineData = new LineData(tempDataSet, humDataSet);
            chartEnvironment.setData(lineData);

            // 刷新图表
            chartEnvironment.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化存储数据
     */
    private void initStorageTask() {
        try {
            storageHandler = new Handler();
            storageRunnable = new Runnable() {
                @Override
                public void run() {
                    // 执行数据存储操作
                    saveSensorDataToDatabase();
                    // 循环执行
                    if (storageHandler != null) {
                        storageHandler.postDelayed(this, STORAGE_INTERVAL);
                    }
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 摄像头初始化
     */
    private void initTp() {
        try {
            this.m_TPSDKContext = this.m_TPOpenSDK.getSDKContext();
            this.m_TPSDKContext.appReqStart(false, new IPCReqListener() {
                @Override
                public int callBack(IPCReqResponse ipcReqResponse) {
                    if (ipcReqResponse.mError != 0) {
                        Log.e(TAG, "底层app启动失败");
                        return 0;
                    }
                    m_IPCDeviceContext = m_TPSDKContext.getDevCtx();
                    long l = m_IPCDeviceContext.initDev(Tp_ip, 80);

                    if (l < 0) {
                        Log.e(TAG, "设备初始化失败，底层指针为:" + l);
                        return 0;
                    }

                    m_IPCDevice = new IPCDevice(l);
                    m_IPCDeviceContext.reqLogin(m_IPCDevice, "123456", new IPCReqListener() {
                        @Override
                        public int callBack(IPCReqResponse ipcReqResponse) {
                            if (ipcReqResponse.mError != 0) {
                                Log.e(TAG, "摄像头登录失败");
                                return 0;
                            }
                            m_IPCDeviceContext.reqConnectDev(m_IPCDevice, new IPCReqListener() {
                                @Override
                                public int callBack(IPCReqResponse ipcReqResponse) {
                                    if (ipcReqResponse.mError != 0) {
                                        Log.e(TAG, "设备能力集获取失败");
                                        return 0;
                                    }
                                    m_IPCDeviceContext.reqGetVideoPort(m_IPCDevice, new IPCReqListener() {
                                        @Override
                                        public int callBack(IPCReqResponse ipcReqResponse) {
                                            if (ipcReqResponse.mError != 0) {
                                                Log.e(TAG, "视频端口获取失败");
                                                return 0;
                                            }
                                            Log.i(TAG, "视频端口获取成功");
                                            can_play = true;
                                            return 0;
                                        }
                                    });
                                    return 0;
                                }
                            });
                            return 0;
                        }
                    });
                    return 0;
                }
            });
        } catch (Exception e) {
            Log.e("TAG", "摄像头初始化异常: " + e.toString());
        }
    }


    /**
     * 初始化所有UI控件
     */
    private void initViews(View view) {
        try {
            // 初始化顶部状态信息控件
            headerCameraStatus = view.findViewById(R.id.header_camera_status);
            headerAlarmStatus = view.findViewById(R.id.header_alarm_status);
            headerDoorStatus = view.findViewById(R.id.header_door_status);
            headerCameraIndicator = view.findViewById(R.id.header_camera_indicator);
            headerAlarmIndicator = view.findViewById(R.id.header_alarm_indicator);
            headerDoorIndicator = view.findViewById(R.id.header_door_indicator);

            // 初始化摄像头监控区域控件
            video = view.findViewById(R.id.video);
            ivCameraPreview = view.findViewById(R.id.iv_camera_preview);
            btnCameraUp = view.findViewById(R.id.btn_camera_up);
            btnCameraLeft = view.findViewById(R.id.btn_camera_left);
            btnCameraRight = view.findViewById(R.id.btn_camera_right);
            btnCameraDown = view.findViewById(R.id.btn_camera_down);
            btnCameraToggle = view.findViewById(R.id.btn_camera_toggle);
            llCameraOffline = view.findViewById(R.id.ll_camera_offline);
            llCameraControls = view.findViewById(R.id.ll_camera_controls);

            // 初始化环境数据控件
            tvTemperatureValue = view.findViewById(R.id.tv_temperature_value);
            tvHumidityValue = view.findViewById(R.id.tv_humidity_value);

            // 初始化传感器状态控件
            tvSmoke = view.findViewById(R.id.tv_smoke);
            tvFire = view.findViewById(R.id.tv_fire);
            tvLaser = view.findViewById(R.id.tv_laser);

            // 初始化设备控制控件
            cardDeviceControl = view.findViewById(R.id.card_device_control);
            ivLamp = view.findViewById(R.id.iv_lamp);
            btnLamp = view.findViewById(R.id.btn_lamp);
            ivDoor = view.findViewById(R.id.iv_door);
            btnDoor = view.findViewById(R.id.btn_door);
            ivFan = view.findViewById(R.id.iv_fan);
            btnFan = view.findViewById(R.id.btn_fan);

            // 初始化图表控件
            chartEnvironment = view.findViewById(R.id.chart_environment);

            //入侵图片按钮
            view.findViewById(R.id.btn_waring).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(requireActivity(), WaringActivity.class));
                }
            });

            if (UserInfo.getUserInfo().getType() == 0) {
                //用户
                llCameraControls.setVisibility(View.GONE);
                cardDeviceControl.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * fragment可见时
     */
    @Override
    public void onResume() {
        super.onResume();
        try {
            if (btn_camera) {
                show_video();
            }

            if (fan_flag) {
                startFanAnimation();
            }
            startDataFetching();
            startStorageTask();

            //加载历史数据并更新图表
            updateChartData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * fragment不可见时
     */
    @Override
    public void onPause() {
        super.onPause();
        try {
            stop_show_video();
            stopDataFetching();
            stopFanAnimation();
            stopStorageTask();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 销毁时
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            stop_show_video();

            if (null != mediaPlayer) {
                mediaPlayer.release();
                mediaPlayer = null;
            }

            if (mediaPlayer != null) {
                try {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                    mediaPlayer.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mediaPlayer = null;
            }

            //销毁风扇动画
            if (null != animator) {
                animator.cancel();
                animator = null;
            }

            // 确保销毁时停止所有数据获取
            stopDataFetching();
            if (dataHandler != null) {
                dataHandler.removeCallbacksAndMessages(null);
                dataHandler = null;
            }
            dataRunnable = null;

            stopStorageTask();
            if (storageHandler != null) {
                storageHandler.removeCallbacksAndMessages(null);
                storageHandler = null;
            }
            storageRunnable = null;

            // 释放图表资源
            if (chartEnvironment != null) {
                chartEnvironment.clear();
                chartEnvironment = null;
            }
            tempEntries = null;
            humEntries = null;
            tempDataSet = null;
            humDataSet = null;
            lineData = null;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}